<?php
namespace app\controllers;

use Yii;
use app\tools\Re;
use app\tools\Curl;
use app\models\User;

class WechatController extends BaseController
{
    //获取openid
    public function actionGetOpenid() {
      $code = Yii::$app->request->post('code', '');
      $appid = Yii::$app->params['ali_config']['appid'];
      $appsecret = Yii::$app->params['ali_config']['appsecret'];
      $curl_url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$appsecret&js_code=$code&grant_type=authorization_code";
      $res = Curl::curl_get($curl_url);
      $res = json_decode($res);
      if ($res->errcode != 0) {
        return Re::data(null, $res->errmsg, Re::ERROR);
      }
      $user_info = User::find()->where(['openid' => $res->openid])->one();
      if (!$user_info) {
        $user_info = new User();
        $user_info->openid = $res->openid;
        $user_info->created_at = time();
      }
      if (!$user_info->save()) {
        return Re::data(null, '用户信息保存失败', Re::ERROR);
      }
      return Re::data(['data' => $user_info]);
    }

    //更新用户信息
    public function actionSaveInvitation(){
      $openid = Yii::$app->request->post('openid', '');
      $invitation_id = Yii::$app->request->post('invitation_id', 0);
      $user_info = User::find()->where(['openid' => $openid, 'status' => 1])->one();
      if (!$user_info) {
        return Re::data(null, '用户信息读取错误', Re::ERROR);
      }
      if ($invitation_id != $user_info->id && !$user_info->invitation_id) {
        $user_info->invitation_id = $invitation_id;
      }
      $user_info->save();
      return Re::data();
    }

    //更新用户信息
    public function actionUpdateUser() {
      $openid = Yii::$app->request->post('openid', '');
      $nickname = Yii::$app->request->post('nickname', '');
      $name = Yii::$app->request->post('name', '');
      $phone = Yii::$app->request->post('phone', '');
      $icon = Yii::$app->request->post('icon', '');
      $user_info = User::find()->where(['openid' => $openid, 'status' => 1])->one();
      if (!$user_info) {
        return Re::data(null, '用户信息读取错误', Re::ERROR);
      }
      $user_info->nickname = $nickname;
      $user_info->name = $name;
      $user_info->phone = $phone;
      $user_info->icon = $icon;
      if (!$user_info->save()) {
        return Re::data(null, '用户信息保存失败', Re::ERROR);
      }
      return Re::data(['data' => $user_info]);
    }
}
